package com.bianmaba.spring.security.basic.handler;

import com.bianmaba.spring.security.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@ConditionalOnMissingBean({BianmabaSessionInformationExpiredStrategy.class})
public class BianmabaSessionInformationExpiredStrategy implements SessionInformationExpiredStrategy {

    private static final Logger LOGGER = LoggerFactory.getLogger(BianmabaSessionInformationExpiredStrategy.class);

    public BianmabaSessionInformationExpiredStrategy() {
    }

    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent e) throws IOException, ServletException {
        HttpServletRequest request = e.getRequest();
        String requestType = request.getHeader("request_type");
        if ("ajax".equals(requestType)) {
            HttpServletResponse response = e.getResponse();
            Map<String, Object> result = new HashMap<String, Object>(0);
            result.put("success", false);
            result.put("status", 401.1);
            result.put("statusText", "Session expired");
            result.put("securityMessage", true);
            result.put("result", "用户会话过期或已在其它电脑登录，请重新登录！");
            result.put("failureType", e.getClass().getSimpleName());
            ResponseUtil.writeJson(response, result, 401);
            LOGGER.error(result.get("result").toString(), e);
        } else {
            HttpServletResponse response = e.getResponse();
            response.getWriter().print(
                    "This session has been expired (possibly due to multiple concurrent "
                            + "logins being attempted as the same user).");
            response.flushBuffer();
        }
    }
}
